package ar.edu.unq.dodb.morphia.store;

import ar.edu.unq.dodb.morphia.model.Entidad;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.MapperOptions;
import com.google.code.morphia.mapping.cache.DefaultEntityCache;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.mongodb.Mongo;

public class MorphiaUtils {

	private static Morphia morphia;
	private static Mongo mongo;
	private static Datastore ds;
	private static final EntityCache cache = new DefaultEntityCache();

	public synchronized static Datastore dataStore() {
		return MorphiaUtils.ds;
	}

	public static EntityCache getCache() {
		return MorphiaUtils.cache;
	}

	public static Morphia getMorphia() {
		return MorphiaUtils.morphia;
	}

	public static synchronized void initialize(final String dbName) {
		try {
			final Morphia temporalMorphia = new Morphia();
			MorphiaUtils.toMap(temporalMorphia);
			MorphiaUtils.morphia = temporalMorphia;
			final Morphia morph = MorphiaUtils.morphia;
			final MapperOptions options = new MapperOptions();
			options.actLikeSerializer = true;
			options.ignoreFinals = true;
			options.storeNulls = true;
			morph.getMapper().setOptions(options);
			MorphiaUtils.mongo = new Mongo();
			MorphiaUtils.ds = morph.createDatastore(MorphiaUtils.mongo, dbName);
			MorphiaUtils.ds.ensureIndexes();
		} catch (final Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static void toMap(final Morphia temporalMorphia) {
		temporalMorphia.mapPackageFromClass(Entidad.class);
	}

}
